package com.bjb.vr.manager.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.alibaba.fastjson.JSONObject;
import com.bjb.vr.common.ao.OptClassifyAo;
import com.bjb.vr.common.ao.OptFeatureAo;
import com.bjb.vr.common.ao.OptTopicAo;
import com.bjb.vr.common.ao.ResContentAo;
import com.bjb.vr.common.constant.EncryptConstant;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.constant.TokenConstants;
import com.bjb.vr.common.exception.CommonException;
import com.bjb.vr.common.result.BaseResult;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.BeanMapUtil;
import com.bjb.vr.common.utils.DateTimeUtil;
import com.bjb.vr.common.utils.OkHttpUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.bjb.vr.manager.properties.ServerInfoProperties;
import com.bjb.vr.manager.utils.AccessRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * @description:
 * @author: hujingbo
 * @create: 2022-12-26 10:29
 **/
@Slf4j
@Service
public class HttpOperationService {

    @Resource
    private ServerInfoProperties serverInfoProperties;

    /**
     * 调用云端资源服务接口
     *
     * @param object
     * @return
     */
    public CommonResult postCloudApi(Object object) {
        Map<String, Object> params = null;
        try {
            String postUrl = getRequestUrl();
            params = BeanMapUtil.beanToMap(object);
            generateSign(params);
            // 封装请求参数
            Map<String, String> headers = AccessRequestUtil.takeHeaders();
            Iterator<Map.Entry<String, Object>> iterator = params.entrySet().stream().iterator();
            OkHttpUtil builder = OkHttpUtil.builder();
            builder.url(postUrl).addHeader("Content-Type", "application/json; charset=utf-8").addHeader(TokenConstants.AUTHORIZATION, headers.get(TokenConstants.AUTHORIZATION.toLowerCase()));
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                builder.addParam(entry.getKey(), entry.getValue().toString());
            }
            // 解析响应体
            String response = builder.post(true).sync();
            JSONObject parseObject = JSONObject.parseObject(response);
            if (parseObject.get("success").equals(true)) {
                Object data = parseObject.get("data");
                return CommonResult.Ok().setResult(data);
            } else {
                Object message = parseObject.get("message");
                return CommonResult.Fail(message.toString());
            }
        } catch (Exception e) {
            throw new CommonException(e.getMessage());
        }
    }

    /**
     * 获取签名
     *
     * @return
     */
    private Map<String, Object> generateSign(Map<String, Object> params) {
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        StringBuilder builder = new StringBuilder();
        String tenantId = umsAccountVo.getTenantId();
        String requestId = UUID.fastUUID().toString();
        String requestTime = DateTimeUtil.nowStrTime();
        // 生成签名
        String data = builder.append(tenantId).append(requestId).append(requestTime).toString();
        byte[] key = EncryptConstant.ENCRYPT_KEY.getBytes();
        HMac mac = new HMac(HmacAlgorithm.HmacMD5, key);
        String signature = mac.digestHex(data);
        // 保存数据
        params.put("tenantId", tenantId);
        params.put("requestId", requestId);
        params.put("requestTime", requestTime);
        params.put("signature", signature);
        return params;
    }

    /**
     * 获取请求地址
     *
     * @return
     */
    private String getRequestUrl() {
        String requestURI = AccessRequestUtil.getRequestURI().replace("manager", "operation").replace("v1", "v1/cloud").trim();
        log.info("云端资源请求路径,requestURI = " + requestURI);
        return serverInfoProperties.getCloudServerUrl() + requestURI;
    }

    /**
     * 查询推荐位列表数据
     *
     * @param optFeatureAo
     * @return
     */
    public CommonResult queryFeatureList(OptFeatureAo optFeatureAo) {
        return postCloudApi(optFeatureAo);
    }

    /**
     * 查询资源详情
     *
     * @param resContentAo
     * @return
     */
    public BaseResult queryResourcesOne(ResContentAo resContentAo) {
        return postCloudApi(resContentAo);
    }

    /**
     * 查询分类推荐列表数据
     *
     * @param optClassifyAo
     * @return
     */
    public BaseResult queryClassifyList(OptClassifyAo optClassifyAo) {
        return postCloudApi(optClassifyAo);
    }

    /**
     * 查询资源列表
     *
     * @param resContentAo
     * @return
     */
    public BaseResult queryResourcesList(ResContentAo resContentAo) {
        return postCloudApi(resContentAo);
    }

    /**
     * 查询专题推荐列表数据
     *
     * @param optTopicAo
     * @return
     */
    public BaseResult queryTopicList(OptTopicAo optTopicAo) {
        return postCloudApi(optTopicAo);
    }
}
